<template>
  <div class="page-container">
    <page-form :model="form" ref="formRef" :rules="rules" layout="vertical">
      <card class="car-model-999" title="个人信息" toggle divider-margin="0 0 20px">
        <page-form-row>
          <page-form-item style="position: relative" field="memberName" label="姓名" required size="1/3">
            <a-input v-model="form.memberName" placeholder="请输入" :max-length="50" allow-clear />
          </page-form-item>
          <page-form-item style="position: relative" field="phone" label="手机号" required size="1/3">
            <a-input v-model="form.phone" placeholder="请输入" :max-length="11" @keyup="keyupPhone" allow-clear />
          </page-form-item>
          <page-form-item style="position: relative" field="sex" label="性别" size="1/3">
            <a-select v-model="form.sex" placeholder="请选择" allow-clear>
              <a-option v-for="item in memberPageData.sexMap" :key="item.value" :value="item.value" :label="item.label" />
            </a-select>
          </page-form-item>
          <page-form-item style="position: relative" field="clientId" label="所属企业" size="1/3">
            <remote-select v-model="form.clientId" placeholder="请选择" :params="{}" type="member_clientInfo" />
          </page-form-item>
          <page-form-item label="电子合同认证状态" size="1/3" v-if="routePrams.id">
            <div class="status" :class="getClassName(form)">
              {{ form.ecAuthenticationStatusName }}
            </div>
            <template v-if="form.ecAuthenticationStatus === 0"> 原因: {{ form.authenticationFailedReason }} </template>
          </page-form-item>
        </page-form-row>
      </card>
      <card title="证件上传" toggle>
        <a-alert>
          <template #icon> <icon-exclamation-circle /> </template>支持jpg、jpeg、png格式，建议分辨率300*225，建议图片文件大小不超过8MB。
        </a-alert>
        <div class="flex upload-wrapper">
          <div class="upload-width upload-wrapper" style="display: flex">
            <upload-img title="证件正页" v-model="form.idCardFrontFileId" @change="uploadChange($event, '1')" single margin />
            <upload-img title="证件副页" v-model="form.idCardReverseFileId" @change="uploadChange($event, '2')" single margin />
          </div>
          <div class="flex-1 mt-20px">
            <page-form-row>
              <page-form-item field="cardType" label="证件类型" size="1/2">
                <a-select v-model="form.cardType" placeholder="请选择">
                  <a-option v-for="item in memberPageData.cardTypeMap" :key="item.value" :value="item.value" :label="item.label" />
                </a-select>
              </page-form-item>
              <page-form-item field="cardNumber" label="证件号" size="1/2">
                <i-input v-model="form.cardNumber" :max-length="18" @keyup="keyupCard" allow-clear />
              </page-form-item>
              <page-form-item field="cardAddress" label="证件住址" size="1">
                <i-input v-model="form.cardAddress" :max-length="100" allow-clear />
              </page-form-item>
              <page-form-item field="identityExpireTime" label="证件到期日" size="1/2">
                <template #label-extra>
                  <a-checkbox v-model="form.identityLong" @change="identityLongChange">长期</a-checkbox>
                </template>
                <i-date-picker
                  class="w-full"
                  v-model="form.identityExpireTime"
                  @change="identityExpireTimeChange"
                  value-format="YYYY-MM-DD"
                />
              </page-form-item>
            </page-form-row>
          </div>
        </div>
      </card>
      <card title="驾驶证上传" toggle>
        <div class="flex upload-wrapper">
          <div class="upload-width upload-wrapper driver-img" style="display: flex">
            <upload-img title="驾驶证正页" v-model="form.driverFrontFileId" @change="uploadChange($event, '3')" single margin />
            <upload-img title="驾驶证副页" v-model="form.driverReverseFileId" @change="uploadChange($event, '4')" single margin />
          </div>
          <div class="flex-1">
            <page-form-row>
              <page-form-item field="driverNumber" label="驾驶证号" size="1/2">
                <a-input-search
                  v-if="form.cardType == 0"
                  placeholder="请输入"
                  v-model="form.driverNumber"
                  button-text="同身份证号"
                  @search="copycard"
                  search-button
                  :max-length="18"
                  @keyup="keyupDrive"
                  allow-clear
                />
                <i-input v-else v-model="form.driverNumber" placeholder="请输入" :max-length="30" />
              </page-form-item>
              <page-form-item field="driverExpireTime" label="驾驶证到期日" size="1/2">
                <template #label-extra>
                  <a-checkbox v-model="form.driverLong" @change="driverLongChange">长期</a-checkbox>
                </template>
                <i-date-picker class="w-full" v-model="form.driverExpireTime" @change="driverExpireTimeChange" value-format="YYYY-MM-DD" />
              </page-form-item>
            </page-form-row>
          </div>
        </div>
      </card>
      <card title="紧急联系人" toggle :showDivider="false">
        <page-form-row>
          <page-form-item field="emergencyContactName" label="姓名" size="1/3">
            <i-input v-model="form.emergencyContactName" :max-length="30" allow-clear />
          </page-form-item>
          <page-form-item field="emergencyContactPhone" label="手机号" size="1/3">
            <a-input v-model="form.emergencyContactPhone" placeholder="请输入" :max-length="11" allow-clear @input="onInput" />
          </page-form-item>
        </page-form-row>
      </card>
    </page-form>
  </div>

  <page-form-footer :ok-loading="okLoading" @ok="submitFn" />
</template>

<script setup name="MemberPersonFrom">
  import { ref, provide, watch } from 'vue'
  import { useRoute } from 'vue-router'
  import { usePageDict } from '@/hooks/useDict'
  import {
    createUpdate,
    resolveIdCardFront,
    resolveIdCardBack,
    resolveDriveCardFront,
    resolveDriveCardBack,
    getDetail,
    resolvePassport,
  } from '@/api/market/member'
  import useUserStore from '@/store/modules/user'
  import useNavigate from '@/hooks/useNavigate'
  import { cloneDeep } from 'lodash-es'
  import { Modal } from '@arco-design/web-vue'

  const { navigateBack } = useNavigate()
  const route = useRoute()
  const routePrams = route.params

  // 获取商户配置详情
  const userStore = useUserStore()
  userStore.setEpDetail()

  const cloneDeepResult = ref()
  const getDetails = (id) => {
    getDetail({ id: id }).then((res) => {
      form.value = res.result
      cloneDeepResult.value = cloneDeep(res.result)
      if (form.value.identityLong == 0 || form.value.identityLong == null) {
        form.value.identityLong = false
      } else {
        form.value.identityLong = true
      }
      if (form.value.driverLong == 0 || form.value.driverLong == null) {
        form.value.driverLong = false
      } else {
        form.value.driverLong = true
      }
    })
  }

  const getClassName = (item) => {
    // -1: 未认证 0: 认证失败 1: 认证成功 2: 认证中
    if (item.ecAuthenticationStatus === -1) {
      return 'status-unauth'
    } else if (item.ecAuthenticationStatus === 0) {
      return 'status-failed'
    } else if (item.ecAuthenticationStatus === 1) {
      return 'status-success'
    } else if (item.ecAuthenticationStatus === 2) {
      return 'status-wait'
    }
  }

  const onInput = (value) => {
    form.value.emergencyContactPhone = value.replace(/\D/g, '')
  }

  const keyupPhone = () => {
    let result = form.value.phone
    form.value.phone = result.replace(/\D/g, '')
  }
  const keyupCard = () => {
    let result = form.value.cardNumber
    form.value.cardNumber = result.replace(/[^A-Za-z\d]/g, '')
  }
  const keyupDrive = () => {
    let result = form.value.driverNumber
    form.value.driverNumber = result.replace(/[^A-Za-z\d]/g, '')
  }
  console.log(routePrams)
  if (routePrams.id) {
    getDetails(routePrams.id)
  }

  const form = ref({
    cardType: 0,
  })

  // 关于选择日期与选择长期
  const identityLongChange = (e) => {
    form.value.identityLong = e ? 1 : ''
    form.value.identityExpireTime = e ? '' : form.value.identityExpireTime
  }
  const driverLongChange = (e) => {
    form.value.driverLong = e ? 1 : ''
    form.value.driverExpireTime = e ? '' : form.value.driverExpireTime
  }
  const identityExpireTimeChange = (e) => {
    form.value.identityLong = e ? !form.value.identityExpireTime : form.value.identityLong
  }
  const driverExpireTimeChange = (e) => {
    form.value.driverLong = e ? !form.value.driverExpireTime : form.value.driverLong
  }

  const uploadChange = (fileId, type) => {
    if (!fileId) {
      return false
    }
    // 后台未开通ocr识别开关，不执行ocr识别
    if (!userStore.epOcrSwitch) {
      return
    }
    if (type == '1' && fileId) {
      if (form.value.cardType == 0) {
        // 身份证
        resolveIdCardFront({ fileId: fileId })
          .then((res) => {
            form.value.memberName = res.result.name
            form.value.cardNumber = res.result.number
            form.value.cardAddress = res.result.address
          })
          .catch((err) => {
            console.log(err)
            // 产品要求不清空图片
          })
      }
      if (form.value.cardType == 1) {
        // 护照
        resolvePassport({ fileId: fileId })
          .then((res) => {
            form.value.memberName = res.result.name
            form.value.cardNumber = res.result.personId
            // form.value.identityExpireTime = res.result.issueDate
            // form.value.identityLong = res.result.expireDate
          })
          .catch((err) => {
            console.log(err)
            // 产品要求不清空图片
          })
      }
    }
    if (type == '2' && fileId) {
      if (form.value.cardType == 0) {
        // 身份证
        resolveIdCardBack({ fileId: fileId }).then((res) => {
          if (res.result.endDate == '长期') {
            form.value.identityLong = 1
          } else {
            form.value.identityExpireTime = res.result.endDate
          }
          // form.value.identityLong = e ? !form.value.identityExpireTime : form.value.identityLong
        })
      }
      if (form.value.cardType == 1) {
        // 护照
      }
    }
    if (type == '3' && fileId) {
      resolveDriveCardFront({ fileId: fileId }).then((res) => {
        form.value.driverNumber = res.result.number
        form.value.driverExpireTime = res.result.validEndDate
        // form.value.driverLong = e ? !form.value.driverExpireTime : form.value.driverLong
      })
    }
    if (type == '4' && fileId) {
      resolveDriveCardBack({ fileId: fileId }).then(() => {})
    }
  }

  const validatorPhone = (value, callback) => {
    if (value.length == 11) {
      // callback('MIMA');
    } else {
      callback('手机号格式不正确')
    }
  }
  const rules = {
    memberName: { required: true, message: '请填写姓名' },
    phone: [
      { required: true, message: '请填写手机号' },
      { validator: validatorPhone, trigger: 'change' },
    ],
  }
  const memberPageData = usePageDict('memberPageData')
  provide('dict', memberPageData)

  const copycard = () => {
    console.log('同身份证号')
    form.value.driverNumber = form.value.cardNumber
  }

  const isChangePhone = ref(false)
  watch(
    () => form.value.phone,
    (val) => {
      if (routePrams.id) {
        if (val != cloneDeepResult.value.phone) {
          isChangePhone.value = true
        }
        if (val == cloneDeepResult.value.phone) {
          isChangePhone.value = false
        }
      }
    }
  )

  const isChangeMemberName = ref(false)
  watch(
    () => form.value.memberName,
    (val) => {
      if (routePrams.id) {
        if (val != cloneDeepResult.value.memberName) {
          isChangeMemberName.value = true
        }
        if (val == cloneDeepResult.value.memberName) {
          isChangeMemberName.value = false
        }
      }
    }
  )

  const formRef = ref()
  const okLoading = ref(false)
  const submitFn = (noticeSuccess) => {
    formRef.value.validate((error) => {
      if (!error) {
        const param = {
          ...form.value,
        }

        const submitTmp = () => {
          if (form.value.identityLong == false || !form.value.identityLong) {
            param.identityLong = 0
          } else {
            param.identityLong = 1
          }
          if (form.value.driverLong == false || !form.value.driverLong) {
            param.driverLong = 0
          } else {
            param.driverLong = 1
          }
          if (form.value.emergencyContactPhone == '') {
            param.emergencyContactPhone = undefined
          }
          okLoading.value = true
          createUpdate(param)
            .then(() => {
              noticeSuccess()
              navigateBack()
            })
            .finally(() => {
              okLoading.value = false
            })
        }

        if (
          (isChangePhone.value || isChangeMemberName.value) &&
          (form.value.ecAuthenticationStatus === 0 || form.value.ecAuthenticationStatus === 1 || form.value.ecAuthenticationStatus === 2)
        ) {
          let content = ''
          if (isChangePhone.value) {
            content = '个人会员已发起电子合同认证，如修改电话号码，下次签署合同时，需重新认证，是否修改手机号？'
          }
          if (isChangeMemberName.value) {
            content = '个人会员已发起电子合同认证，如修改姓名，下次签署合同时，需重新认证，是否修改姓名？'
          }
          if (isChangePhone.value && isChangeMemberName.value) {
            content = '个人会员已发起电子合同认证，如修改姓名和电话号码，下次签署合同时，需重新认证，是否修改姓名和手机号？'
          }

          Modal.confirm({
            title: '提示',
            simple: true,
            cancelText: '取消',
            okText: '确认',
            bodyStyle: {
              'text-align': 'center',
            },
            content,
            onOk: () => {
              submitTmp()
            },
            // onCancel: () => {
            //   param.phone = cloneDeepResult.value.phone
            //   submitTmp()
            // },
          })
        } else {
          submitTmp()
        }
      }
    })
  }
</script>

<style lang="less" scoped>
  .status {
    display: flex;
    justify-content: center;
    align-items: center;
    max-width: 76px;
    height: 20px;
    padding: 0 8px;
    font-size: 12px;
    font-weight: 500;
    border-radius: 2px 2px 2px 2px;
    border: 1px solid;
    color: rgba(185, 187, 196, 1);
    border-color: rgba(229, 230, 235, 1);
    background-color: rgba(242, 243, 245, 1);

    &.status-unauth {
      color: rgba(185, 187, 196, 1);
      border-color: rgba(229, 230, 235, 1);
      background-color: rgba(242, 243, 245, 1);
    }
    &.status-failed {
      color: rgba(245, 63, 63, 1);
      border-color: rgba(245, 63, 63, 1);
      background-color: rgba(255, 236, 232, 1);
    }
    &.status-success {
      color: rgba(0, 180, 42, 1);
      border-color: rgba(0, 180, 42, 1);
      background-color: rgba(232, 255, 234, 1);
    }
    &.status-wait {
      color: rgba(255, 125, 0, 1);
      border-color: rgba(255, 125, 0, 1);
      background-color: rgba(255, 247, 232, 1);
    }
  }
  .upload-width {
    width: 37%;
  }
  .mt-20px {
    margin-top: 16px;
  }
  :deep(.arco-card-header) {
    padding: 0 0 16px !important;
  }
  :deep(.driver-img > .upload-imag) {
    margin-top: 0 !important;
  }
</style>
